//
// Created by Jeffrey Wei on 2022/10/11.
// 此组件应为单独的核心组件库中,外部AppDelegate继承即可
// 重写微服务,若需要,也可单独重写UIApplicationDelegate的声明周期函数

import Foundation
import UIKit

open class CoreAppDelegate: UIResponder, UIApplicationDelegate {
    open var rootViewController: UIViewController {
        fatalError("子类需要实现控制器")
    }

    open var services: [Service] {
        []
    }

    private lazy var _services = services

    public var window: UIWindow?

    open func application(_ application: UIApplication,
                          didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
    {
        UserDefaults.standard.setValue(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
        /// 启动所有微服务,所有的start在window之前执行
        _services.forEach { $0.start(launchOptions: launchOptions) }
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = rootViewController
        window?.makeKeyAndVisible()
        /// didFinishLaunchingWithOptions在window之后执行
        return services.reduce(true) {
            $0 && ($1.application?(application, didFinishLaunchingWithOptions: launchOptions)) ?? true
        }
    }

    public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
        services.reduce(true) {
            $0 && ($1.application?(app, open: url, options: options)) ?? true
        }
    }

    public func applicationDidEnterBackground(_ application: UIApplication) {
        _services.forEach { $0.applicationDidEnterBackground?(application) }
    }

    public func applicationWillEnterForeground(_ application: UIApplication) {
        _services.forEach { $0.applicationWillEnterForeground?(application) }
    }

    public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        _services.forEach { $0.application?(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) }
    }

    public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        _services.forEach { $0.application?(application, didFailToRegisterForRemoteNotificationsWithError: error) }
    }

    public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        _services.forEach { $0.application?(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler) }
    }
}
